package com.along.study.common;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;

public class CustomMsgDecoder extends LengthFieldBasedFrameDecoder {

    public CustomMsgDecoder(int maxFrameLength, int lengthFieldOffset, int lengthFieldLength, int lengthAdjustment,
                            int initialBytesToStrip) {
        super(maxFrameLength, lengthFieldOffset, lengthFieldLength, lengthAdjustment, initialBytesToStrip);
    }

    public CustomMsgDecoder(int maxFrameLength, int lengthFieldOffset, int lengthFieldLength, int lengthAdjustment,
                            int initialBytesToStrip, boolean failFast) {
        super(maxFrameLength, lengthFieldOffset, lengthFieldLength, lengthAdjustment, initialBytesToStrip, failFast);
    }

    @Override
    protected CustomMsg decode(ChannelHandlerContext ctx, ByteBuf in2) throws Exception {
        ByteBuf in = (ByteBuf) super.decode(ctx, in2);
        if (in == null) {
            return null;
        }

        if (in.readableBytes() < 4) {
            return null;
        }

        CustomMsg customMsg = new CustomMsg();
        int dataLength = in.readInt();//读了4个字节
        byte type = in.readByte();//读了1个字节
        in.readByte();//对应编码中的无无意义字节写入
        byte[] from = new byte[10];
        byte[] to = new byte[10];
        in.readBytes(from);
        in.readBytes(to);
        //长度 4个字节 type 1个字节，1个填充无意义字节，from 和 to 共20个字节
        byte[] data = new byte[dataLength - 26];
        in.readBytes(data);

        customMsg.setType(type);
        customMsg.setFrom(from);
        customMsg.setTo(to);
        customMsg.setData(data);
        in.release();

        return customMsg;
    }
}
